const data = [
    { id: 1, name: "A", parentId: null },
    { id: 2, name: "B", parentId: 1 },
    { id: 3, name: "C", parentId: 1 },
    { id: 4, name: "D", parentId: 2 },
    { id: 5, name: "E", parentId: 2 },
    { id: 6, name: "F", parentId: 3 },
];
function arrayToTree(data) {
    const map = new Map();
    const tree = [];

    // 先遍历一遍，构建映射表
    data.forEach(item => map.set(item.id, { ...item, children: [] }));
    // 再遍历一次，填充树形结构
    data.forEach(item => {
        if (item.parentId !== null) {
            const parent = map.get(item.parentId);
            if (parent) {
                parent.children.push(map.get(item.id));
            }
        } else {
            tree.push(map.get(item.id));
        }
    });

    return tree;
}

console.log(JSON.stringify(arrayToTree(data), null, 2));
